<template>
	<view>
		<view v-if="viders ==true" style="width: 100vw;height: 100vh;background: #FFFFFF;">
			<x-lottie style="width:100%;height:100%;" :option="{
			                path:require('../../static/json/AI.json')
			}" />
		</view>
		<hx-navbar ref="hxnb" :config="config" />
		<view v-if="viders ==false" style="background-color:#1f232f ;" @touchmove.stop.prevent="moveHandle">
			<view class="container">
				<scroll-view v-if="loaded" class="content" scroll-y="true" :style="'width: 100%;height:'+height +'px;'"
					:scroll-top="scrollTop" scroll-with-animation="true" id="commentContainer">
					<!-- 用来获取消息体高度 -->
					<view id="chat-list">
						<!-- 消息 -->
						<view class="item" v-for="(x,i) in msgList" :key="i">
							<!-- 用户消息 头像可选加入-->
							<view>
								<view class="chat-item human-item" v-if="x.content!=''">
									<!-- 	<image v-if="!x.my" class="chat-img" src="../../static/..." mode="aspectFill" ></image> -->

									<view class="chat chat-human">
										<text style="word-break: break-all;">{{x.content}}</text>
									</view>
									<!-- <image class="chat-img " src="../../static/..." mode="aspectFill" ></image> -->
								</view>
							</view>
							<!-- loading是显示 -->
							<!-- 机器人消息 -->
							<view v-if="x.gptContent!=''" class="chat-item ai-item">
								<!--  <view class="chat-img flex-row-center">
									<image style="height: 75rpx;width: 75rpx;" src="../../static/robt.png" mode="aspectFit"></image>
								</view> -->
								<view class="chat1 chat-ai" @longpress="copyText(x.gptContent)">
									<!-- <text style="word-break: break-all;" @longpress="copyText(x.msg)">{{x.msg}}</text> -->
									<!-- <textarea :value="content"></textarea> -->
									{{x.gptContent}}
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- 			<view class="bottom-textarea">
				<view id="bottom">
					<view class="flex align-center" :style="{'width':title==true? 200 +'rpx' :'' }"
						style="background-color: #FFFFFF;border-radius: 54rpx;padding: 5rpx;margin:0 70rpx 10rpx 30rpx ;">
						<x-lottie style="width:94rpx;height:94rpx;" :option="{
			                path:require('../../static/json/a.json')
			}" />
						<x-lottie style="width:76rpx;height:76rpx;" :option="{
			                path:require('../../static/json/fankui.json')
			}" />
						<view style="color: rgba(30,30,30,0.5);" v-if="title==false">有什么可以帮您的吗?</view>
					</view>

					<view style="font-size: 55rpx;display:flex;margin:6rpx;justify-content: space-between;">
						<input v-model="msg" class="uni-input dh-input" type="text" :disabled="msgLoad"
							style="background-color:#FFFFFF;width: 600rpx;margin-bottom: 30rpx;" @confirm="check"
							confirm-type="send" placeholder-class="my-neirong-sm" placeholder="聊两句吧~"
							cursor-spacing="10" :adjust-position="false" />
						<u-button type="primary" @click="check" :disabled="msgLoad"
							:customStyle="{'width':'80rpx','height':'80rpx'}" shape="circle" color="#1cbbb4"
							icon="play-right" style="margin-left: 15rpx;"></u-button>
					</view>
				</view>
				<u-toast ref="uToast"></u-toast>
			</view> -->
		</view>
		<view style="width: 100%;height:150rpx;background-color: #1c202b;color: #FFFFFF;padding:20rpx ;">
			<view class="flex align-center justify-between">
				<view style="border: 1rpx solid #3c7bbe; border-radius: 50%;">
					<x-lottie style="width:76rpx;height:76rpx;" :option="{
				                 path:require('../../static/json/fankui.json')
				 }" />
				</view>
				<view>
					<!-- <img src="/static/53.png" style="width: 100rpx;height: 100rpx;" alt=""> -->
					<input v-model="msg" class=" dh-input uni-input" type="text"
						style="width: 600rpx;border-radius: 30rpx;background-color: #1c202b;margin-right: 40rpx;border: 1rpx solid white;"
						@confirm="check" confirm-type="send" placeholder-class="my-neirong-sm" placeholder="聊两句吧~"
						cursor-spacing="0" />
				</view>
			</view>
		</view>
		<view style="color: #FFF;padding: 0 25rpx 20rpx 25rpx;">
			<tabbar :type="0"></tabbar>
		</view>
		<!-- 底部安全距离 -->
		<view style="height: 50rpx;"></view>
	</view>
</template>
<script>
	import {
		webScroct,
		ws
	} from "@/common/webscroct.js"
	import tabbar from "@/components/tabbar.vue"
	export default {
		components: {
			tabbar
		},
		data() {
			return {
				// 标题栏配置
				config: {
					title: "共厂家居智能小助手",
					back: true,
					// backgroundColor: '#1f232f',
					color: '#1f232f'
				},
				default_height: 0,
				inputBottom: 0,
				height: 0,
				scrollTop: 1000,
				msgLoad: false,
				anData: {},
				userId: "",
				animationData: {},
				showTow: false,
				msgList: [{
					gptContent: '',
					content: ''
				}],
				msg: "",
				loaded: false,
				viders: true,
				uuid: '',
				title: false,
				content: "",
				index: 0,
			}
		},
		computed: {
			safeHeight() {
				if (this.inputBottom > 60) {
					return '0';
				} else {
					return 'env(safe-area-inset-bottom)';
				}
			}
		},
		onUnload() {
			uni.closeSocket()
		},
		onLoad() {
			this.ims()
			uni.onKeyboardHeightChange(res => {
				this.inputBottom = res.height;
				console.log(this.inputBottom, '小辞职信辞职信')
				let win = uni.getWindowInfo();
				let height = win.windowHeight;
				height = height - win.safeAreaInsets.bottom - 45 - this.inputBottom;
				this.height = height;
				this.height = this.default_height - this.inputBottom;
				this.scrollTop += 2000; //滚到底部
			})
			uni.getSystemInfo({
				success: res => {
					let height = res.windowHeight;
					// #ifndef H5
					height -= 45;
					// #endif
					height = height - res.safeAreaInsets.bottom - 75;
					this.height = height - 75;
					this.default_height = height;
				}
			})
			// this.base = getApp().globalData.base;
			// let settings = getApp().globalData.settings;
			// console.log(getApp, '不持续创新')
			// this.msgList[0].msg = settings.first_sentence;
			// this.base = getApp().globalData.base;
			// http.get(this.base + 'login', {}).then(res => {
			// 	this.data = res.data;
			// })
			this.loaded = true;
		},
		mounted() {},
		methods: {
			moveHandle() {
				return false;
			},
			his(e) {
				uni.request({
					// url: 'http://192.168.31.25:9000/user/tabBar/public/hasGetGptHistory', //本地url地址
					url: 'http://121.40.61.169:9000/user/tabBar/public/hasGetGptHistory', //线上地址
					data: {
						imei: e,
					},
					method: "POST",
					header: {
						'Content-type': 'application/x-www-form-urlencoded;',
					},
					success: (res) => {
						this.msgList = res.data.result
						console.log(res.data.result.length, '尹元康好帅')
						this.msgList.push({
							gptContent: '',
							content: ''
						})
						if (res.data.result.length >= 1) {
							this.index = res.data.result.length - 1
						}
						console.log(this.index, '打我')
					},
					fail: (error) => {}
				});
			},
			ims() {
				this.getDeviceInfo().then(deviceInfo => {
						console.log("成功", deviceInfo);
						let data = {
							imei: deviceInfo.uuid
						}
						this.uuid = data.imei
						this.openSocket(deviceInfo.uuid)
						this.$api.hasReplayGpt(data).then((res) => {
							if (res.data.result == 0) {
								this.viders = true
								setTimeout(() => {
									this.viders = false
								}, 10050)
							} else {
								this.viders = false
							}
						})
						setTimeout(() => {
							this.his(this.uuid)
						}, 1000)

					})
					.catch(error => {
						console.error('获取设备信息失败：', error);

					});

			},
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					plus.device.getInfo({
						success: function(deviceInfo) {
							resolve(deviceInfo);

						},
						fail: function(error) {
							console.log("fail: ", error);
							uni.showToast({
								title: "无法连接到智能服务",
								duration: 3000,
								complete() {
									uni.switchTab({
										url: "/pages/tabbar/clientEndTabbar/ClientHome",
									})
								}
							})
							reject(error);
						}
					});
				});
			},
			check() {
				this.msgLoad = true
				// 消息为空不做任何操作
				if (this.msg == "") {
					return;
				}
				let data = {
					message: this.msg,
					imei: this.uuid,
					type: 0
				}
				this.title = false
				let content = JSON.stringify(data)
				console.log('行政村创造性', this.mesaead)
				uni.sendSocketMessage({
					data: content,
					complete(res) {
						console.log("呆呆鸟: ", res);
						console.log('带嗲鸟', data)
					}
				})
			},
			scrollToButtom() {
				let query = uni.createSelectorQuery().in(this)
				query.select('#commentContainer').boundingClientRect()
				query.select('#chat-list').boundingClientRect()
				query.exec((res) => {
					//如果子元素高度大于父元素高度(显示高度)
					if (res[1].height > res[0].height) {
						//计算出二者差值就是需要滚动的距离
						this.scrollTop = res[1].height - res[0].height
					}
				})
			},
			openSocket(uuid) {
				console.log("!", uuid);
				let url = ws + webScroct + '/gptSocket/' + uuid + '/1'
				console.log("dfdssdsdf", url)
				// 连接
				this.SocketTask = uni.connectSocket({
					url: url,
					fail(e) {
						console.log("连接失败")
					},
					success(e) {
						console.log(e, "连接成功")
					},
					complete: () => {}
				});
				console.log('socket', this.SocketTask)
				// 监听开启
				this.SocketTask.onOpen(() => {
					// 将连接状态设为已连接
					console.log('将连接状态设为已连接');

				})
				// 监听关闭
				this.SocketTask.onClose((e) => {
					console.log('连接状态关闭', e);
					uni.closeSocket();
				})
				// 监听错误
				this.SocketTask.onError((e) => {
					console.log(e, '连接错误');
				})
				// 监听接收信息
				this.SocketTask.onMessage((e) => {
					console.log('监听接收信息', e);
					if (e.data == "结end束") {
						this.msg = ''
						this.index++
						this.msgLoad = false
						let lastEnd = this.msgList[this.msgList.length - 1].gptContent
						console.log("lastEnd: ", lastEnd);
						if (lastEnd.indexOf("系统异常") != -1) {
							this.msgList[this.msgList.length - 1].gptContent = "系统太火爆啦，请等待一小会后再继续提问吧~";
							this.$forceUpdate()
						}
						console.log("this.msgList[this.index].content: ", );
						this.msgList.push({
							"gptContent": '',
							"content": ''
						})
						this.title = false
					} else {
						this.msgList[this.index].content = this.msg
						this.msgList[this.index].gptContent += e.data
						setTimeout(() => {
							this.scrollToButtom()
						}, 500)
					}
				})
			},
			goMy(e) {
				/*
				uni.showToast({
					title: '暂未开放，敬请期待',
					icon: 'none'
				})
				return;*/
				uni.navigateTo({
					url: '/pages/my/my'
				})
			},
			copyText(msg) {
				uni.setClipboardData({
					data: msg,
					success() {
						uni.showToast({
							title: '已复制到剪贴板',
							icon: 'none',
							position: 'top'
						})
					}
				})
			},
			/*
			hideKey() {
				uni.hideKeyboard()
			},*/
		}
	}
</script>

<style>
	page {
		background: #1c202b;
	}

	.container {
		display: flex;
		flex-direction: column;
	}

	.content {
		flex-grow: 1;
		overflow: auto;
	}

	.bottom-textarea {
		position: fixed;
		bottom: 0rpx;
	}

	.chat-item {
		display: flex;
	}

	.human-item {
		justify-content: flex-end;
	}

	.chat {
		padding: 8px 12px;
		margin: 5px 10px 5px 10px;
		font-size: 14px;
		background-image: url('/static/53.png');
		background-size: cover;
		background-repeat: no-repeat;
		color: #ffffff;
	}

	.chat1 {
		padding: 8px 12px;
		margin: 5px 10px 5px 10px;
		font-size: 14px;
		background-image: url('/static/54.png');
		background-size: cover;
		background-repeat: no-repeat;
		color: #1E1E1E;
	}

	.item:first-child .chat {
		margin-top: 20px;
	}

	.chat-human {
		border-radius: 18px 0px 18px 18px;
		color: #fff;
		background-color: #442c24;
	}

	.chat-ai {
		border-radius: 0px 18px 18px 18px;
		background-color: #f9f9f9;
	}



	.my-neirong-sm {
		font-size: 14px;
	}

	.bottom-dh-char {
		background-color: #f9f9f9;
		width: 100%;
		height: 110rpx;
	}

	.center-box {
		width: 720rpx;
		padding-left: 25rpx;
	}

	.btn {
		height: 80rpx;
		width: 80rpx;
		margin-left: 15rpx;

	}

	.flex-row-start {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
	}

	.hui-box {
		width: 750rpx;
		height: 100%;

	}

	.dh-input {
		width: 70%;
		height: 80rpx;
		border-radius: 10rpx;
		padding-left: 25rpx;
		margin-left: 15rpx;

		background-color: #FFFFFF;
		font-size: 14px;

	}

	.box-normal {
		width: 750rpx;
		height: 180px;
		background-color: #FFFFFF;
	}

	.tb-text view {
		font-size: 65rpx;
	}

	.tb-text text {
		font-size: 25rpx;
		color: #737373;
	}

	.chat-img {
		border-radius: 50%;
		width: 100rpx;
		height: 100rpx;
		background-color: #f7f7f7;
	}


	.tb-nv {
		width: 50rpx;
		height: 50rpx;
	}

	.cs {
		width: 30rpx;
		transform: scale(30deg);
	}

	.csgo {
		width: 650rpx;
	}

	.textxxssb {
		position: relative;
		top: 5rpx;
		font-size: 40rpx;
		animation: change 0.5s ease infinite alternate;
		animation-delay: 0.4s;
	}

	.textxxssb:nth-child(2) {
		animation-delay: 0.2s;
	}

	.textxxssb:nth-child(3) {
		animation-delay: 0.3s;
	}

	.textxxssb:nth-child(4) {
		animation-delay: 0.4s;
	}

	.textxxssb:nth-child(5) {
		animation-delay: 0.1s;
	}

	@keyframes change {
		100% {
			top: -8rpx;

		}
	}
</style>
